package com.distributer.gateway.configuration;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import com.distributer.gateway.hander.BusinessThreadPool;
import com.distributer.gateway.mapper.ServiceGroupMapper;
import com.distributer.gateway.mapper.ServiceInfoMapper;
import com.distributer.gateway.model.ServiceGroup;
import com.distributer.gateway.model.ServiceInfo;

@Configuration
@Order(Ordered.LOWEST_PRECEDENCE)
public class GateWayConfigura {
	
	@Autowired
	private ServiceGroupMapper serviceGroupMapper;
	@Autowired
	private ServiceInfoMapper serviceInfoMapper;
	
	private final ScheduledExecutorService scheduler =  Executors.newSingleThreadScheduledExecutor(
            new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r, "OperationProductDataPullListenner");
                    thread.setDaemon(true);
                    return thread;
                }
            }
    );
	
	@Bean(name="handlerPools")
	public Map<String, BusinessThreadPool> handlerThreadInit(JedisPool jedisPool){
		Map<String, BusinessThreadPool> handlerPools = new HashMap<String, BusinessThreadPool>();
		List<ServiceGroup> serviceGroups = serviceGroupMapper.loadAll();
		for (ServiceGroup serviceGroup : serviceGroups) {
			BusinessThreadPool businessThreadPool = new BusinessThreadPool(serviceGroup.getMinThreadCount(), serviceGroup.getMaxThreadCount(), serviceGroup.getTaskQueueLength(), serviceGroup.getThreadName());
			businessThreadPool.setServiceGroup(serviceGroup);
			handlerPools.put(serviceGroup.getServiceGroupName(), businessThreadPool);
			//初始化服务组下的service列表
			List<ServiceInfo> serviceInfos = serviceInfoMapper.queryServiceInfosByGroupCode(serviceGroup.getServiceGroupCode());
			/**
			 * 1:将服务信息初始化到redis(分布式轮询算法需要用到)
			 * 2:启动定时任务检查服务的可用性
			 */
		}
		return handlerPools;
	}
	
	@Bean(name="jedisPool")
	public JedisPool jedisPoolInit(){
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(100);
		config.setMaxIdle(5);
		config.setMaxWaitMillis(1000 * 10); 
		config.setTestOnBorrow(true);
		return new JedisPool(config, "192.168.57.134", 6379);
	}
}
